package xyz.jcat.common.util;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.util.DigestUtils;

import java.util.UUID;

public class CodeUtils {

    /**
     * 密码加密
     *
     * @param pwd
     * @return
     */
    public static String pwdEncrypt(String pwd) {
        return pwdEncrypt(pwd, RandomUtils.nextInt(8, 14));
    }

    /**
     * 密码加密
     *
     * @param pwd
     * @param logRounds bcrypt算法获取盐的参数
     * @return
     */
    public static String pwdEncrypt(String pwd, int logRounds) {
        return BCrypt.hashpw(pwd, BCrypt.gensalt(logRounds));
    }

    /**
     * 校验密码
     *
     * @param pwd          原密码
     * @param encryptedPwd 加密后密码
     * @return
     */
    public static boolean checkPwd(String pwd, String encryptedPwd) {
        return BCrypt.checkpw(pwd, encryptedPwd);
    }

    public static String genAccessTokenByUUID() {
        return MD5(UUID.randomUUID().toString());
    }

    public static String MD5(String target) {
        return DigestUtils.md5DigestAsHex(target.getBytes());
    }

    public static String fillZeroForward(int target, int length) {
        StringBuilder sb = new StringBuilder();
        String targetString = String.valueOf(target);
        int targetLength = targetString.length();
        if(targetLength >= length) {
            return targetString;
        }
        int times = length - targetLength;
        for (int i = 0; i < times; i++) {
            sb.append(0);
        }
        return sb.append(target).toString();
    }

}
